<?php

namespace app\api\model\xykeep;

use think\Model;
use traits\model\SoftDelete;
use think\Request;

class Course extends Model
{

    use SoftDelete;

    // 表名
    protected $name = 'xykeep_course';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    //列表动态隐藏字段
    public static $list_hidden = ['intro', 'rule', 'crowd', 'note','updatetime','deletetime'];

    // 追加属性
    protected $append = [
        'status_text',
        'total_sales'
    ];

    protected function base($query)
    {
        $query->where('status','normal')->where('deletetime',null)->order('id desc');
    }

    public static function getDetail($id)
    {
        $user = User::info();

        $course = self::where(['id'=>$id,'status'=>'normal'])->with(['favorite' => function ($query) use ($user) {
            $user_id = empty($user) ? 0 : $user->id;
            return $query->where(['user_id' => $user_id]);
        }])->find();

        $pattern = '/(http|https)\:\/\/([a-z]+\.){1,3}[a-z]+/';
        $request = Request::instance();
        $domain = $request->domain();

        $course['intro'] = preg_replace($pattern,$domain,$course['intro']);
        return $course;
       
    }

    public function getImageAttr($value, $data)
    {
        if (!empty($value)) return cdnurl($value, true);
    }

    /**
     * params 请求参数
     */
    public static function getList($params)
    {
        extract($params);
        $where = [
            'status' => 'normal'
        ];

        $order = 'weigh desc,id desc';

        if (isset($search) && $search !== '') {
            $where['name|intro'] = ['like', "%$search%"];
        }

        if (isset($ids) && $ids !== '') {
            $order = 'field(id, ' . $ids . ')';
            $idsArray = explode(',', $ids);
            $where['id'] = ['in', $idsArray];
        }


        $course = self::where($where);

        $order = xykeepFilterSql($order);
        $course = $course->field('*,(sales + show_sales) as total_sales')->orderRaw($order)->order('id desc');

        $cacheKey = 'courselist-' . (isset($page) ? 'page' : 'all') . '-' . md5(json_encode($params));

        // 判断缓存
        $courseCache = cache($cacheKey);
        if ($courseCache) {
            // 存在缓存直接 返回
            $courseCache = json_decode($courseCache, true);
            return $courseCache ? : [];
        } 

        if (isset($page)) {
            $course = $course->paginate($per_page ?? 10);
            $courseData = $course->items();
        } else {
            $course = $courseData = $course->select();
        }

        $data = [];
        if ($courseData) {
            $collection = collection($courseData);
            $data = $collection->hidden(self::$list_hidden);
        }

        if (isset($page)) {
            $course->data = $data;
        } else {
            $course = $data;
            cache($cacheKey, json_encode($course), (600 + mt_rand(0, 300)));
        }

        return $course;
    }

    protected static function init()
    {
        self::afterInsert(function ($row) {
            $pk = $row->getPk();
            $row->getQuery()->where($pk, $row[$pk])->update(['weigh' => $row[$pk]]);
        });
    }


    public function getTotalSalesAttr($value, $data)
    {
        return $data['sales'] + $data['show_sales'];
    }
    
    public function getStatusList()
    {
        return ['normal' => __('显示'),'hidden' => __('隐藏')];
    }

    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function favorite()
    {
        return $this->hasOne('\app\api\model\xykeep\user\Favorite', 'target_id', 'id');
    }

    public function category()
    {
        return $this->belongsTo('app\api\model\xykeep\Category', 'category_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function coach()
    {
        return $this->belongsTo('app\api\model\xykeep\Coach', 'coach_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function store()
    {
        return $this->belongsTo('app\api\model\xykeep\Store', 'store_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
}
